package com.example.sunny.service.dao

import android.content.Context
import android.util.Log
import androidx.core.content.edit
import com.example.sunny.SunnyApplication
import com.example.sunny.pojo.location.MyLocation
import com.example.sunny.pojo.place.Place
import com.google.gson.Gson
import org.litepal.LitePal
import org.litepal.extension.findAll

object PlaceDao {
    fun savePlace(place:Place){
        sharedPreferences().edit{
            putString("place",Gson().toJson(place))
        }
    }

    fun getSavedPlace():Place{
        val placeJson = sharedPreferences().getString("place","")
        return Gson().fromJson(placeJson,Place::class.java)
    }

    fun isPlaceSaved() = sharedPreferences().contains("place")


    private fun sharedPreferences() = SunnyApplication.context.getSharedPreferences("sunny",Context.MODE_PRIVATE)

    fun saveLocation(myLocation: MyLocation){
        myLocation.save()
    }

    fun deleteLocation(){
        LitePal.deleteAll(MyLocation::class.java,)
    }

    fun getLocation(): MyLocation?{
        val listMyLocation = LitePal.findAll<MyLocation>()
        Log.d("PlaceDao",listMyLocation.toString())
        if (listMyLocation==null || listMyLocation.size==0){
            return null
        }
        return listMyLocation[0]
    }

}